package com.xmkj.jijidriver.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.carbean.OrderInfoBean;
import com.common.jiji.entity.BaseJJBean;
import com.common.jiji.entity.JJorderDelBean;
import com.common.jiji.methods.ArriveMethods;
import com.common.jiji.methods.GetOrderDelMethods;
import com.common.jiji.methods.JieDanMethods;
import com.common.jiji.parms.OrderDelJiedanParms;
import com.common.jiji.parms.OrderDelParms;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;

import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.LogUtils;
import com.xmkj.jijidriver.R;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;


import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * Create by leo
 * 创建日期：2018/4/11
 * 描述：
 */

public class OrderFrameActivity extends BaseMvpActivity {
    public static final String ORDERID = "orderid";
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_service)
    TextView tvService;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_begin_address)
    TextView tvBeginAddress;
    @BindView(R.id.tv_address_end)
    TextView tvAddressEnd;
    @BindView(R.id.tv_name_again)
    TextView tvNameAgain;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.et_mobile)
    TextView etMobile;
    @BindView(R.id.tv_create_time)
    TextView tvCreateTime;
    @BindView(R.id.tv_beizhu)
    TextView tvBeizhu;
    @BindView(R.id.tv_stasus)
    TextView tvStasus;
    @BindView(R.id.rl_call)
    RelativeLayout rl_call;



    private int orderid;
    private int status;
    private OrderInfoBean infoBean;
    private JJorderDelBean bean;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_frame;
    }

    @Override
    protected void onViewCreated() {

    }

    @Override
    protected void doLogicFunc() {


        Intent intent = getIntent();
        if (null != intent) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                orderid = bundle.getInt(ORDERID);
                if (EmptyUtils.isNotEmpty(orderid)) {
                    gotoGetOrderInfo();
                }
            }

        }
        attachClickListener(rl_call);


  /*      orderid = intent.getIntExtra(ORDERID, 0);
        if (EmptyUtils.isNotEmpty(orderid)) {
            gotoGetOrderInfo();
        }
*/
        attachClickListener(tvStasus);
        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.ORDER_STATUS_CHANGE) && (Boolean) rxKeyEvent.getValue()) {

                    gotoGetOrderInfo();
                }
            }
        }));
    }

    @Override
    protected void onViewClicked(View view) {
        if (view.getId() == tvStasus.getId()) {
            switch (bean.result.status) {
                case "1": // 去接单
                    gotoJieDan();
                    break;
                case "4": // 确认到达
                    intrueArrive();
                    break;


            }
        } else if(rl_call.getId()==view.getId()){
                    if(EmptyUtils.isEmpty(etMobile.getText().toString())){
                        return;
                    }
            //申请权限
            AndPermission.with(OrderFrameActivity.this)
                    .requestCode(105)
                    .permission(Manifest.permission.CALL_PHONE)
                    .rationale(mRationaleListener)
                    .send();
        }
    }

    private void intrueArrive() {
        showProgressingDialog();
        CommonSubscriber<BaseJJBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                gotoGetOrderInfo();

            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        OrderDelParms loginParms = new OrderDelParms();
        loginParms.orderNo = bean.result.orderNo;
        ArriveMethods.getInstance().beginOrderNow(subscriber, loginParms);
        rxManager.add(subscriber);
    }

    private void gotoJieDan() {
        showProgressingDialog();
        CommonSubscriber<BaseJJBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                gotoGetOrderInfo();

            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        OrderDelJiedanParms loginParms = new OrderDelJiedanParms();
        loginParms.orderNo = bean.result.orderNo;
        JieDanMethods.getInstance().beginOrderNow(subscriber, loginParms);
        rxManager.add(subscriber);
    }


    private void gotoGetOrderInfo() {
        showProgressingDialog();
        CommonSubscriber<JJorderDelBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                bean = (JJorderDelBean) o;
                dismissProgressDialog();
                tvMoney.setText(bean.result.money + "");
                tvService.setText(bean.result.orderTypeStr);
                tvTime.setText(bean.result.beginTime + "--" + bean.result.endTime);
                tvBeginAddress.setText(bean.result.beginAddr);
                tvAddressEnd.setText(bean.result.endAddr);
                tvNameAgain.setText(bean.result.content);
                etMobile.setText(bean.result.phone);
                tvCreateTime.setText(bean.result.createTime);
                if (EmptyUtils.isNotEmpty(bean.result.remark)) {
                    tvBeizhu.setText(bean.result.remark);
                }
                switch (bean.result.status) {
                    case "1"://等待接单
                        tvStasus.setEnabled(true);
                        tvStasus.setText("确认接单");
                        break;
                    case "2"://等待接单
                        tvStasus.setEnabled(false);
                        tvStasus.setText("待支付");
                        break;
                    case "3"://等待接单
                        tvStasus.setEnabled(false);
                        tvStasus.setText("已完成");
                        break;
                    case "4"://已接单
                        tvStasus.setEnabled(true);
                        tvStasus.setText("到达位置");
                        break;
                    case "5":
                        tvStasus.setEnabled(false);
                        tvStasus.setText("已到达");
                        break;
                    case "6"://等待接单
                        tvStasus.setEnabled(false);
                        tvStasus.setText("乘客已上车");
                        break;
                    case "7"://等待接单
                        tvStasus.setEnabled(false);
                        tvStasus.setText("已取消");
                        break;
                }


            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        OrderDelParms loginParms = new OrderDelParms();
        loginParms.orderId = orderid;

        GetOrderDelMethods.getInstance().getOrderDetailByOrderId(subscriber, loginParms);
        rxManager.add(subscriber);
    }

    @Override
    protected void setNavigation() {
        setNavigationBack("订单详情");
    }


    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }
    //申请权限
    private RationaleListener mRationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            new AlertDialog.Builder(OrderFrameActivity.this)
                    .setTitle("友好提醒")
                    .setMessage("没有权限您不能拨打电话，请把权限赐给我吧!(如果设置不再提示,您可以在设置中打开权限)")
                    .setPositiveButton("好，给你", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();// 用户同意继续申请。
                        }
                    })
                    .setNegativeButton("我拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel(); // 用户拒绝申请。
                        }
                    }).show();
        }
    };

    @PermissionYes(105)
    private void openPic() {
        LogUtils.e("成功回调了-->");
        gotoCall();


    }

    private void gotoCall() {

        showTwoDialog("提示", etMobile.getText().toString(), "拨打", "取消");
        setOnDialogViewClick(new OnDialogViewClick() {
            @Override
            public void leftViewClick() {
//                        showToastMsg("hha");
                Intent intent = new Intent(); // 意图对象：动作 + 数据
                intent.setAction(Intent.ACTION_CALL); // 设置动作
                Uri data = Uri.parse("tel:" + etMobile.getText().toString()); // 设置数据
                intent.setData(data);
                startActivity(intent); // 激活Activity组件
            }

            @Override
            public void singleViewClick() {

            }
        });


    }

    @PermissionNo(105)
    private void injectPic() {
        LogUtils.e("失败回调了-->");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，剩下的 AndPermission 自动完成。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }


}
